package io.gbznt.modules.buss.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.gbznt.modules.buss.entity.BussFarmlandInfoEntity;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import io.gbznt.common.utils.DocUtil;
import io.gbznt.common.utils.FileConfigReader;
import io.gbznt.common.utils.PageUtils;
import io.gbznt.common.utils.R;
import io.gbznt.common.utils.ShiroUtils;
import io.gbznt.common.validator.ValidatorUtils;
import io.gbznt.common.validator.group.AddGroup;
import io.gbznt.common.validator.group.UpdateGroup;
import io.gbznt.modules.buss.constatnt.RtuEquipmentTypeEnum;
import io.gbznt.modules.buss.entity.BussRtuEquipmentEntity;
import io.gbznt.modules.buss.entity.BussRtuInfoEntity;
import io.gbznt.modules.buss.service.BussFarmlandInfoService;
import io.gbznt.modules.buss.service.BussRtuEquipmentService;
import io.gbznt.modules.buss.service.BussRtuInfoService;


/**
 * RTU设备
 *
 * @author gbznt
 * @email http://www.gbznt.com/
 * @date 2019-04-20 15:48:34
 */
@RestController
@RequestMapping("buss/bussrtuequipment")
public class BussRtuEquipmentController {

    @Autowired
    private BussRtuEquipmentService bussRtuEquipmentService;
    @Autowired
    private BussFarmlandInfoService bussFarmlandInfoService;
    @Autowired
    private BussRtuInfoService bussRtuInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("buss:bussrtuequipment:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = bussRtuEquipmentService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("buss:bussrtuequipment:info")
    public R info(@PathVariable("id") String id){
        BussRtuEquipmentEntity bussRtuEquipment = bussRtuEquipmentService.getById(id);

        BussRtuInfoEntity bussRtuInfoEntity = bussRtuInfoService.getById(
                bussRtuEquipment.getRtuId());
        if(null != bussRtuInfoEntity) {
            bussRtuEquipment.setRtuSerialNum(bussRtuInfoEntity.getSerialNum());
        }

        return R.ok().put("bussRtuEquipment", bussRtuEquipment);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("buss:bussrtuequipment:save")
    public R save(@RequestBody BussRtuEquipmentEntity bussRtuEquipment){
    	ValidatorUtils.validateEntity(bussRtuEquipment,AddGroup.class);

        Integer namesNum = bussRtuEquipmentService.count(
                new QueryWrapper<BussRtuEquipmentEntity>().eq("name",bussRtuEquipment.getName()));
        if(namesNum >= 1){
            return R.error("该设备名称已存在");
        }

   	 	bussRtuEquipment.setCreateId(ShiroUtils.getUserId()+"");
   	 	bussRtuEquipment.setCreateName(ShiroUtils.getUserName());
    	bussRtuEquipment.setCreateTime(new Date());

        BussRtuInfoEntity bussRtuInfoEntity = bussRtuInfoService.getById(
                bussRtuEquipment.getRtuId());
        if(null != bussRtuInfoEntity) {
            bussRtuEquipment.setDeptId(bussRtuInfoEntity.getDeptId());
        }

        bussRtuEquipmentService.save(bussRtuEquipment);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("buss:bussrtuequipment:update")
    public R update(@RequestBody BussRtuEquipmentEntity bussRtuEquipment){
        ValidatorUtils.validateEntity(bussRtuEquipment,AddGroup.class);

        Integer namesNum = bussRtuEquipmentService.count(
                new QueryWrapper<BussRtuEquipmentEntity>().eq("name",bussRtuEquipment.getName())
                .ne("id",bussRtuEquipment.getId())
        );
        if(namesNum >= 1){
            return R.error("该设备名称已存在");
        }

        bussRtuEquipment.setUpdateId(ShiroUtils.getUserId()+"");
        bussRtuEquipment.setUpdateName(ShiroUtils.getUserName());
    	bussRtuEquipment.setUpdateTime(new Date());

        BussRtuInfoEntity bussRtuInfoEntity = bussRtuInfoService.getById(
                bussRtuEquipment.getRtuId());
        if(null != bussRtuInfoEntity) {
            bussRtuEquipment.setDeptId(bussRtuInfoEntity.getDeptId());
        }

        Boolean re = bussRtuEquipmentService.updateById(bussRtuEquipment);//全部更新
        
        return re?R.ok():R.oldVersion();
    }

    /**
     * 保存
     */
    @RequestMapping("/saveFileAndData")
    @RequiresPermissions("buss:bussrtuequipment:save")
    public R saveFileAndData(BussRtuEquipmentEntity bussRtuEquipment, HttpServletRequest request) {
        MultipartFile multipartFile = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
                    MultipartHttpServletRequest.class);
            multipartFile = multipartRequest.getFile("file");

            if (null == multipartFile) {// 有更改文件
                return R.error("未上传文件");
            }
        }

        String rootPath = FileConfigReader.getUploadFilePath();
        R createDirRes = DocUtil.createDir(multipartFile, rootPath);
        if ((Integer) createDirRes.get("code") != 0) {
            return createDirRes;
        }

        File insertFile = (File) createDirRes.get("insertFile");

        try {
            multipartFile.transferTo(insertFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return R.error("上传文件出错!!!");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传文件出错");
        }

        // 获取当前用户的部门信息
        bussRtuEquipment.setCreateId(ShiroUtils.getUserId());
        bussRtuEquipment.setCreateName(ShiroUtils.getUserName());
        bussRtuEquipment.setCreateTime(new Date());
        bussRtuEquipment.setIconImg(insertFile.getPath());
        // 拿rtu设备所属基地id
        BussRtuInfoEntity bussRtuInfoEntity = bussRtuInfoService.getById(
                bussRtuEquipment.getRtuId());
        if(null != bussRtuInfoEntity) {
            bussRtuEquipment.setDeptId(bussRtuInfoEntity.getDeptId());
        }

        ValidatorUtils.validateEntity(bussRtuEquipment, AddGroup.class);
        Boolean re = bussRtuEquipmentService.save(bussRtuEquipment);

        return re ? R.ok() : R.error();
    }

    /**
     * 修改
     */
    @RequestMapping("/updateFileAndData")
    @RequiresPermissions("buss:bussrtuequipment:update")
    public R updateFileAndData(BussRtuEquipmentEntity bussRtuEquipment, HttpServletRequest request) {
        MultipartFile multipartFile = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
                    MultipartHttpServletRequest.class);
            multipartFile = multipartRequest.getFile("file");

            if (null != multipartFile) {// 有更改文件
                String rootPath = FileConfigReader.getUploadFilePath();
                R createDirRes = DocUtil.createDir(multipartFile, rootPath);
                if ((Integer) createDirRes.get("code") != 0) {
                    return createDirRes;
                }

                File insertFile = (File) createDirRes.get("insertFile");
                try {
                    multipartFile.transferTo(insertFile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                    return R.error("上传文件出错!!!");
                } catch (IOException e) {
                    e.printStackTrace();
                    return R.error("上传文件出错");
                }
                bussRtuEquipment.setIconImg(insertFile.getPath());
            }
        }

        ValidatorUtils.validateEntity(bussRtuEquipment, UpdateGroup.class);

        bussRtuEquipment.setUpdateId(ShiroUtils.getUserId());
        bussRtuEquipment.setUpdateName(ShiroUtils.getUserName());
        bussRtuEquipment.setUpdateTime(new Date());
        // 拿rtu设备所属基地id
        BussRtuInfoEntity bussRtuInfoEntity = bussRtuInfoService.getById(
                bussRtuEquipment.getRtuId());
        if(null != bussRtuInfoEntity) {
            bussRtuEquipment.setDeptId(bussRtuInfoEntity.getDeptId());
        }

        Boolean re = bussRtuEquipmentService.updateById(bussRtuEquipment);

        return re ? R.ok() : R.oldVersion();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("buss:bussrtuequipment:delete")
    public R delete(@RequestBody String[] ids){
        bussRtuEquipmentService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * @description 获取设备类型
     * @author guoqiang
     * @email rd_guoqiang@139.com
     * @date 2019-04-28
     * @params  * @param
     * @return io.gbznt.common.utils.R
     */
    @RequestMapping("/getRtuEquipmentTypes")
    public R getRtuEquipmentTypes(){
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (RtuEquipmentTypeEnum enumObj: RtuEquipmentTypeEnum.values()) {
            Map<String,Object> map = new HashMap<>();
            map.put("value",enumObj.getValue());
            map.put("text",enumObj.getDescription());
            mapList.add(map);
        }
        
        return R.ok().put("list",mapList);
    }

}
